package com.quectel.cms.controller.grid;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.dto.GridMemberDto;
import com.quectel.core.module.grid.dto.GridMemberGridBindingDto;
import com.quectel.core.module.grid.service.GridMemberGridBindingService;
import com.quectel.core.module.grid.service.GridMemberService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/02/03 15:45
 */
@RestController
@RequestMapping("gridMember")
@Tag(name = "GridMemberController", description = "网格员信息管理表相关api")
public class GridMemberController extends BaseController {

    @DubboReference
    private GridMemberService gridMemberService;
    @DubboReference
    private GridService gridService;
    @DubboReference
    private GridMemberGridBindingService gridMemberGridBindingService;

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "gridMember:list")
    @Operation(summary = "网格员的分页查询列表")
    public Response<Page<GridMemberDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = gridMemberService.queryTotal(request.getParams());

        List<GridMemberDto> list = null;
        if (total > 0) {
            list = gridMemberService.queryList(request.getParams());
            for (GridMemberDto member : list) {
                List<GridDto> result = new ArrayList<>();
                List<GridMemberGridBindingDto> gridMemberGridBindingDtos =
                        gridMemberGridBindingService.selectListByMemberId(member.getId());
                if (CollectionUtils.isNotEmpty(gridMemberGridBindingDtos)) {
                    for (GridMemberGridBindingDto memberGridBinding : gridMemberGridBindingDtos) {
                        GridDto gridDto = gridService.selectCacheById(memberGridBinding.getGridId());
                        if (gridDto != null) {
                            result.add(gridDto);
                        }
                    }
                }
                member.setGridCount(result.size());
                member.setGridList(result);
            }
        } else {
            list = new ArrayList<>();
        }

        Page<GridMemberDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridMemberDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "gridMember:edit")
    @Operation(summary = "查询单条网格员记录")
    public Response<GridMemberDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridMemberDto gridMemberDto = gridMemberService.selectById(id);
        List<GridDto> gridList = new ArrayList<>();


        // 填充已经绑定的网格

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(LambdaUtil.getFieldName(GridMemberGridBindingDto::getGridMemberId), id);
        List<GridMemberGridBindingDto> grids = gridMemberGridBindingService.queryList(queryMap);
        for (GridMemberGridBindingDto record : grids) {
            GridDto gridDto = gridService.selectCacheById(record.getGridId());
            if (gridDto != null) {
                gridList.add(gridDto);
            }
        }
        gridMemberDto.setGridList(gridList);

        return Response.<GridMemberDto>ok().wrap(gridMemberDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "gridMember:info")
    @Operation(summary = "查询单条网格员记录")
    public Response<GridMemberDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridMemberDto gridMemberDto = gridMemberService.selectById(id);
        List<GridDto> result = new ArrayList<>();
        List<GridMemberGridBindingDto> gridMemberGridBindingDtos =
                gridMemberGridBindingService.selectListByMemberId(gridMemberDto.getId());
        if (CollectionUtils.isNotEmpty(gridMemberGridBindingDtos)) {
            for (GridMemberGridBindingDto memberGridBinding : gridMemberGridBindingDtos) {
                GridDto gridDto = gridService.selectCacheById(memberGridBinding.getGridId());
                if (gridDto != null) {
                    result.add(gridDto);
                }
            }
        }
        gridMemberDto.setGridCount(result.size());
        gridMemberDto.setGridList(result);

        return Response.<GridMemberDto>ok().wrap(gridMemberDto);
    }

    /**
     * 保存
     *
     * @param gridMemberDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "gridMember:edit")
    @Operation(summary = "保存单条网格员记录")
    public Response<Object> save(@RequestBody @Validated GridMemberDto gridMemberDto) {

        //填充基础数据
        fillSaveCommonData(gridMemberDto);

        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(GridMemberDto::getTenantId), SessionHolder.getSysUser().getTenantId());
        params.put(LambdaUtil.getFieldName(GridMemberDto::getJobNo), gridMemberDto.getJobNo());

        if (gridMemberService.queryTotal(params) >= 1) {
            return Response.error("网格员工号已存在");
        }

        gridMemberService.saveOrUpdate(gridMemberDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param gridMemberDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "gridMember:edit")
    @Operation(summary = "修改单条网格员记录")
    public Response<Object> update(@RequestBody @Validated GridMemberDto gridMemberDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridMemberDto.getId()));
        if (gridMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        params.clear();
        params.put(LambdaUtil.getFieldName(GridMemberDto::getTenantId), SessionHolder.getSysUser().getTenantId());
        params.put(LambdaUtil.getFieldName(GridMemberDto::getJobNo), gridMemberDto.getJobNo());

        GridMemberDto gridMember = gridMemberService.selectById(gridMemberDto.getId());

        if (gridMemberService.queryTotal(params) >= 1 && !gridMember.getJobNo().equals(gridMemberDto.getJobNo())) {
            return Response.error("网格员工号已存在");
        }

        //填充基础数据
        fillEditCommonData(gridMemberDto);

        gridMemberService.saveOrUpdate(gridMemberDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "gridMember:delete")
    @Operation(summary = "批量删除存在的网格员记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (gridMemberService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridMemberService.deleteBatch(ids);

        return Response.ok();
    }
}
